﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Location;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using BasicInformation.Infrastructure.Interface;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Location
{
    public class UpdateLocationHandler : IRequestHandler<UpdateLocationCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<DelLocationHandler> logger;
        private readonly IMapper mapper;

        public UpdateLocationHandler(DatabaseContext db, ILogger<DelLocationHandler> logger,IMapper mapper)
        {
            this.db = db;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(UpdateLocationCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var location = db.SqlSugar.Queryable<LocationModel>().Where(x => x.LocationId == request.LocationId).First();
            //if (location == null)
            //{
            //    result.Msg = "你要修改的用户不存在";
            //    result.Code = ApiEnum.Fail;
            //    logger.LogError(result.Msg);
            //    return Task.FromResult(result);
            //}
            //var model = locationRepo.GetAll().Where(x => x.LocationName == request.LocationName).Count();
            //if (model == 1)
            //{
            //    result.Msg = "库位名称已存在";
            //    result.Code = ApiEnum.Fail;
            //    logger.LogError(result.Msg);
            //    return Task.FromResult(result);
            //}
            location = mapper.Map(request, location);
            int r =await db.SqlSugar.Updateable(location).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "库位管理修改成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "库位管理修改失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
